import java.util.*;
import java.util.stream.Collectors;

/**
 * XML字符串生成工具类
 * 提供生成XML格式字符串和按字母排序的功能
 * 
 * @author AI Assistant
 * @version 1.0
 */
public class XmlStringGeneratorUtil {
    
    /**
     * 生成简单的XML元素
     * 
     * @param tagName 标签名
     * @param content 标签内容
     * @return XML字符串
     */
    public static String generateSimpleElement(String tagName, String content) {
        if (tagName == null || tagName.trim().isEmpty()) {
            throw new IllegalArgumentException("标签名不能为空");
        }
        
        String sortedContent = content != null ? sortStringAlphabetically(content) : "";
        return String.format("<%s>%s</%s>", tagName, sortedContent, tagName);
    }
    
    /**
     * 生成带属性的XML元素
     * 
     * @param tagName 标签名
     * @param attributes 属性Map
     * @param content 标签内容
     * @return XML字符串
     */
    public static String generateElementWithAttributes(String tagName, Map<String, String> attributes, String content) {
        if (tagName == null || tagName.trim().isEmpty()) {
            throw new IllegalArgumentException("标签名不能为空");
        }
        
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<").append(tagName);
        
        // 添加属性（按属性名排序）
        if (attributes != null && !attributes.isEmpty()) {
            attributes.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .forEach(entry -> xmlBuilder.append(" ")
                            .append(entry.getKey())
                            .append("=\"")
                            .append(entry.getValue())
                            .append("\""));
        }
        
        xmlBuilder.append(">");
        
        // 添加内容（按字母排序）
        String sortedContent = content != null ? sortStringAlphabetically(content) : "";
        xmlBuilder.append(sortedContent);
        
        xmlBuilder.append("</").append(tagName).append(">");
        
        return xmlBuilder.toString();
    }
    
    /**
     * 生成完整的XML文档
     * 
     * @param rootElement 根元素名
     * @param elements 子元素列表
     * @param encoding 编码格式，默认UTF-8
     * @return 完整的XML文档字符串
     */
    public static String generateXmlDocument(String rootElement, List<XmlElement> elements, String encoding) {
        if (encoding == null || encoding.trim().isEmpty()) {
            encoding = "UTF-8";
        }
        
        StringBuilder xmlBuilder = new StringBuilder();
        
        // XML声明
        xmlBuilder.append("<?xml version=\"1.0\" encoding=\"").append(encoding).append("\"?>\n");
        
        // 根元素开始标签
        xmlBuilder.append("<").append(rootElement).append(">\n");
        
        // 添加子元素（按标签名排序）
        if (elements != null) {
            elements.stream()
                    .sorted(Comparator.comparing(XmlElement::getTagName))
                    .forEach(element -> {
                        xmlBuilder.append("  ").append(element.toXmlString()).append("\n");
                    });
        }
        
        // 根元素结束标签
        xmlBuilder.append("</").append(rootElement).append(">");
        
        return xmlBuilder.toString();
    }
    
    /**
     * 将字符串按字母顺序排序
     * 
     * @param input 输入字符串
     * @return 排序后的字符串
     */
    public static String sortStringAlphabetically(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        
        return input.chars()
                .sorted()
                .collect(StringBuilder::new, 
                        StringBuilder::appendCodePoint, 
                        StringBuilder::append)
                .toString();
    }
    
    /**
     * 将字符串列表按字母顺序排序并连接
     * 
     * @param strings 字符串列表
     * @param delimiter 分隔符
     * @return 排序后连接的字符串
     */
    public static String sortAndJoinStrings(List<String> strings, String delimiter) {
        if (strings == null || strings.isEmpty()) {
            return "";
        }
        
        return strings.stream()
                .filter(Objects::nonNull)
                .map(XmlStringGeneratorUtil::sortStringAlphabetically)
                .sorted()
                .collect(Collectors.joining(delimiter != null ? delimiter : ""));
    }
    
    /**
     * 转义XML特殊字符
     * 
     * @param input 输入字符串
     * @return 转义后的字符串
     */
    public static String escapeXmlSpecialChars(String input) {
        if (input == null) {
            return null;
        }
        
        return input.replace("&", "&amp;")
                   .replace("<", "&lt;")
                   .replace(">", "&gt;")
                   .replace("\"", "&quot;")
                   .replace("'", "&apos;");
    }
    
    /**
     * XML元素内部类
     */
    public static class XmlElement {
        private String tagName;
        private String content;
        private Map<String, String> attributes;
        
        public XmlElement(String tagName, String content) {
            this.tagName = tagName;
            this.content = content;
            this.attributes = new HashMap<>();
        }
        
        public XmlElement(String tagName, String content, Map<String, String> attributes) {
            this.tagName = tagName;
            this.content = content;
            this.attributes = attributes != null ? attributes : new HashMap<>();
        }
        
        public String getTagName() {
            return tagName;
        }
        
        public void setTagName(String tagName) {
            this.tagName = tagName;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
        
        public Map<String, String> getAttributes() {
            return attributes;
        }
        
        public void setAttributes(Map<String, String> attributes) {
            this.attributes = attributes != null ? attributes : new HashMap<>();
        }
        
        public void addAttribute(String key, String value) {
            this.attributes.put(key, value);
        }
        
        public String toXmlString() {
            return generateElementWithAttributes(this.tagName, this.attributes, this.content);
        }
    }
    
    /**
     * 示例用法
     */
    public static void main(String[] args) {
        // 示例1：生成简单元素
        String simpleElement = generateSimpleElement("name", "dcba");
        System.out.println("简单元素: " + simpleElement);
        
        // 示例2：生成带属性的元素
        Map<String, String> attributes = new HashMap<>();
        attributes.put("id", "1");
        attributes.put("type", "text");
        String elementWithAttrs = generateElementWithAttributes("input", attributes, "edcba");
        System.out.println("带属性元素: " + elementWithAttrs);
        
        // 示例3：生成完整XML文档
        List<XmlElement> elements = Arrays.asList(
            new XmlElement("title", "zyxwvu"),
            new XmlElement("author", "fedcba"),
            new XmlElement("date", "2024-01-01")
        );
        
        String xmlDocument = generateXmlDocument("document", elements, "UTF-8");
        System.out.println("完整XML文档:\n" + xmlDocument);
        
        // 示例4：字符串排序
        String sorted = sortStringAlphabetically("hello world");
        System.out.println("排序后字符串: " + sorted);
        
        // 示例5：字符串列表排序连接
        List<String> stringList = Arrays.asList("zebra", "apple", "banana");
        String joinedSorted = sortAndJoinStrings(stringList, ", ");
        System.out.println("排序连接字符串: " + joinedSorted);
    }
} 